<template>
  <Dialog :title="title" v-model="visible" width="90%">
    <el-form ref="formRef" :model="form" :rules="formRules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item align="left" label="名 称" prop="name">
            <el-input
              v-model="form.name"
              :style="{ width: '70%' }"
              clearable
              placeholder="请输入名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="分 类" prop="goodsCategoryId">
            <el-select
              v-model="form.goodsCategoryId"
              filterable
              placeholder="请输入关键词"
              reserve-keyword
            >
              <el-option
                v-for="item in goodsCategoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="货 号" prop="goodsSn">
            <el-input
              v-model="form.goodsSn"
              :style="{ width: '70%' }"
              clearable
              placeholder="请输入货号"
            />
            &nbsp;&nbsp;
            <el-button
              type="primary"
              :disabled="form.goodsSn !== null && form.goodsSn !== undefined && form.goodsSn !== ''"
              @click="goodsSnGen"
              >自动生成</el-button
            >
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="规 格" prop="sku">
            <el-select v-model="form.sku" filterable placeholder="请输入关键词" reserve-keyword>
              <el-option
                v-for="item in skuOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="form.sku === '1'">
          <el-form-item align="left" label="商品规格" prop="sku"
            ><el-container>
              <span v-for="(item, index) in skus">
                <el-header
                  >规格名：<el-input
                    v-model="item.skuKeyName"
                    style="width: 240px"
                    placeholder="请输入规格名"
                    clearable
                /></el-header>
                <el-main
                  >规格值：<el-tag
                    v-for="(itemValue, indexValue) in item.skuValues"
                    :key="indexValue"
                    closable
                    :disable-transitions="false"
                  >
                    {{ itemValue }}
                  </el-tag>
                  <el-input v-if="item.skuValueInptVis" class="w-20" size="small" />
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="skuValueInptVisShow(item)"
                  >
                    + 添加规格值
                  </el-button>
                </el-main></span
              ><el-header>
                <el-button
                  class="button-new-tag"
                  size="small"
                  @click="pushSkus"
                  :disabled="skus.length > 2"
                >
                  + 添加规格项
                </el-button></el-header
              >
            </el-container></el-form-item
          >
        </el-col>

        <el-col v-if="form.sku === '0'" :span="12">
          <el-form-item align="left" label="售价(元)" prop="price">
            <el-input-number v-model="form.price" :min="0.01" label="请输入数字" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.sku === '0'" :span="12">
          <el-form-item align="left" label="市场价(元)" prop="originPrice">
            <el-input-number v-model="form.originPrice" :min="0.01" label="请输入数字" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.sku === '0'" :span="12">
          <el-form-item align="left" label="库存(件)" prop="stock">
            <el-input-number v-model="form.stock" :min="1" label="请输入正整数" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="限购(0为不限购)(件)" prop="quota">
            <el-input-number v-model="form.quota" :min="0" label="请输入整数" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="起售数量(件)" prop="startSaleNum">
            <el-input-number v-model="form.startSaleNum" :min="1" label="请输入正整数" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="计量单位" prop="unit">
            <el-select v-model="form.unit" filterable placeholder="请输入关键词" reserve-keyword>
              <el-option
                v-for="item in unitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="库存减少方式" prop="subStock">
            <el-select
              v-model="form.subStock"
              filterable
              placeholder="请输入关键词"
              reserve-keyword
            >
              <el-option
                v-for="item in subStockOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item align="left" label="物 流" prop="delivery">
            <el-select
              v-model="form.delivery"
              filterable
              placeholder="请输入关键词"
              reserve-keyword
            >
              <el-option
                v-for="item in deliveryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="form.delivery === 'delivery'" :span="12">
          <el-form-item align="left" label="运费承担方式" prop="freightPayer">
            <el-select
              v-model="form.freightPayer"
              filterable
              placeholder="请输入关键词"
              reserve-keyword
            >
              <el-option
                v-for="item in freightPayerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="form.delivery === 'delivery' && form.freightPayer === 'buyer'" :span="12">
          <el-form-item align="left" label="同城运费模板" prop="deliveryTemplateLocaleName">
            <el-select
              v-model="form.deliveryTemplateLocaleName"
              filterable
              placeholder="请输入关键词"
              reserve-keyword
            >
              <el-option
                v-for="item in deliveryTemplateLocaleNameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="form.delivery === 'delivery'" :span="12">
          <el-form-item align="left" label="质量(kg)" prop="mass">
            <el-input-number v-model="form.mass" :min="0" label="请输入正数" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.delivery === 'delivery'" :span="12">
          <el-form-item align="left" label="体积-长度(m)" prop="length">
            <el-input-number v-model="form.length" :min="0" label="请输入正数" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.delivery === 'delivery'" :span="12">
          <el-form-item align="left" label="体积-宽度(m)" prop="breadth">
            <el-input-number v-model="form.breadth" :min="0" label="请输入正数" />
          </el-form-item>
        </el-col>

        <el-col v-if="form.delivery === 'delivery'" :span="12">
          <el-form-item align="left" label="体积-高度(m)" prop="height">
            <el-input-number v-model="form.height" :min="0" label="请输入正数" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item align="left" label="图 片" prop="imgs">
            <UploadImgs />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="loading">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts" name="GoodsSpuForm">
import * as Api from '@/api/userCenter/tradeOrder/goods'
import * as CategoryApi from '@/api/userCenter/tradeOrder/goods/category'
import moment from 'moment'
import * as lodash from 'lodash'
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const title = ref(`编辑信息`) // 弹窗的标题
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const inputVisible = ref(false)
const skus = ref([])
const form = ref({
  id: '',
  name: '',
  sku: '0',

  albumPics: '', // 封面图片
  brandId: null, // 品牌ID
  brandName: '', // 品牌
  deleteStatus: 0,
  detailTitle: '',
  feightTemplateId: 0,
  lowStock: 0,
  newStatus: 0,
  originPrice: 0.01,
  pic: '',
  previewStatus: 0,
  price: 0.01,
  goodsCategoryId: '',
  goodsCategoryName: '请点击选择分类',
  goodsSn: '',
  recommandStatus: 0,
  sale: 0,
  serviceIds: '',
  sort: 0,
  stock: 1,
  subTitle: '',
  unit: 'item',
  usePointLimit: 0, // 使用积分限制
  verifyStatus: '1',
  mass: 0, // 重量
  delivery: 'eticket',
  invoice: 'none',
  length: 0,
  breadth: 0,
  height: 0,
  subStock: 'order',
  freightPayer: 'seller',
  quota: 0,
  startSaleNum: 1,
  deliveryTemplateLocaleId: '',
  deliveryTemplateLocaleName: '未设置',
  deliveryTemplateLocaleValuation: '',
  picUrl: ''
})

const imgs = ref([])

const skuOptions = ref([
  { value: '0', label: '单规格', disabled: false },
  { value: '1', label: '多规格', disabled: false }
])

const unitOptions = ref([
  { value: 'item', label: '件' },
  { value: 'mass', label: '质量(公斤kg)' },
  { value: 'volume', label: '体积(毫升ml)' },
  { value: 'time', label: '时间(分minute)' },
  { value: 'length', label: '距离(公里km)' },
  { value: 'area', label: '面积(平方米m2)' }
])

const subStockOptions = ref([
  { value: 'order', label: '下单减库存' },
  { value: 'pay', label: '付款减库存' }
])

const deliveryOptions = ref([
  { value: 'delivery', label: '需要' },
  { value: 'eticket', label: '电子凭证不需要' }
])

const freightPayerOptions = ref([
  { value: 'seller', label: '卖家承担(包邮)' },
  { value: 'buyer', label: '买家承担' }
])

const deliveryTemplateLocaleNameOptions = ref([])

const goodsCategoryOptions = ref([])

const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const getGoodsCategoryOptions = async () => {
  goodsCategoryOptions.value = []
  goodsCategoryOptions.value = await CategoryApi.getList(null)
}

/** 打开弹窗 */
const open = async (id?: string, goodsCategoryId?: string) => {
  getGoodsCategoryOptions()
  visible.value = true

  resetForm()
  imgs.value = []
  // 修改时,设置数据
  if (id) {
    loading.value = true
    form.value.id = id
    try {
      let val = await Api.getById(id)
      if (val) {
        form.value = val

        if (val.imgs && val.imgs.length > 0) {
          for (let i = 0; i < val.imgs.length; i++) {
            const img = { url: val.imgs[i] }

            imgs.value.push(img)
          }
        }
      }
    } catch (t) {
      console.log(t)
    } finally {
      loading.value = false
    }
  }

  if (goodsCategoryId) {
    form.value.goodsCategoryId = goodsCategoryId
  }
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  loading.value = true
  try {
    const data = form.value as Api.Model

    let imgArr: any[] = []

    if (imgs.value && imgs.value.length > 0) {
      for (let i = 0; i < imgs.value.length; i++) {
        const element: any = imgs.value[i]

        imgArr.push(element.url)
      }
    }

    await Api.update(data, imgArr)
    message.success(`操作成功`)
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('提交表单失败')
  } finally {
    loading.value = false
  }
}

/** 重 置表单 */
const resetForm = () => {
  form.value = {
    id: '',
    name: '',
    sku: '0',
    albumPics: '', // 封面图片
    brandId: null, // 品牌ID
    brandName: '', // 品牌
    deleteStatus: 0,
    detailTitle: '',
    feightTemplateId: 0,
    lowStock: 0,
    newStatus: 0,
    originPrice: 0.01,
    pic: '',
    previewStatus: 0,
    price: 0.01,
    goodsCategoryId: '',
    goodsCategoryName: '请点击选择分类',
    goodsSn: '',
    recommandStatus: 0,
    sale: 0,
    serviceIds: '',
    sort: 0,
    stock: 1,
    subTitle: '',
    unit: 'item',
    usePointLimit: 0, // 使用积分限制
    verifyStatus: '1',
    mass: 0, // 重量
    delivery: 'eticket',
    invoice: 'none',
    length: 0,
    breadth: 0,
    height: 0,
    subStock: 'order',
    freightPayer: 'seller',
    quota: 0,
    startSaleNum: 1,
    deliveryTemplateLocaleId: '',
    deliveryTemplateLocaleName: '未设置',
    deliveryTemplateLocaleValuation: '',
    picUrl: ''
  }
  formRef.value?.resetFields()
}

const goodsSnGen = () => {
  form.value.goodsSn =
    moment().format('YYYYMMDDHHmmss') + lodash?.random(1000000000, 9999999999, false)
}

const pushSkus = () => {
  skus.value.push({ name: '', skuValues: [], skuValueInptVis: false })
}

const skuValueInptVisShow = (item) => {
  item.skuValueInptVis = true
}
</script>
